package com.EWS.controller;

import com.EWS.model.UserDto;
import com.EWS.service.UserService;
import com.EWS.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

// 与前端交互在单词系统和设置内进行各种操作
@WebServlet("/userSystemServlet")
public class UserSystemServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    // 转换单词系统页面的信息
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 通过前端登录时提交的会话信息获取此时登录的用户名
        HttpSession session = req.getSession(false); // 不创建新会话，过去前端会话信息
        String userName = (String) session.getAttribute("userName");
        // 获取前端操作的指令
        String opsCode = req.getParameter("opsCode");
        // 点击单词库
        if(opsCode.equals("wordsList")){
            // 通过Dao层查询该用户的学习记录，返回到Service层，返回到这里
            List<UserDto> userDtoList = userService.getUserStudy(userName,"");
            // 将获取到的信息送到前端页面
            req.setAttribute("userDtoList",userDtoList);
            /* //这一步用于退出操作
            HttpSession session = req.getSession();
            session.setAttribute("userName",userName);*/
            req.getRequestDispatcher("wordsList.jsp").forward(req,resp);
        }
        // 点击学习
        if(opsCode.equals("study")){
            // 通过Dao层查询该用户的学习记录，返回到Service层，返回到这里
            List<UserDto> userDtoList = userService.getUserStudy(userName,"");
            // 将获取到的信息送到前端页面
            req.setAttribute("userDtoList",userDtoList);
            req.getRequestDispatcher("study.jsp").forward(req,resp);
        }
        // 点击设置
        if(opsCode.equals("setting")){
            req.getRequestDispatcher("setting.jsp").forward(req,resp);
        }
        // 点击退出
        if(opsCode.equals("loginOut")){
            // 判断当前登录用户的session 是否有效
            session = req.getSession();
            if(session!= null){
                // 让服务器端识别用户端请求的session 失效；
                session.invalidate();
                req.getRequestDispatcher("login.jsp").forward(req,resp);
                System.out.println("用户退出成功");
            }
            else{
                System.out.println("用户退出失败");
            }
        }
    }
}
